package com.example.apiproject.service.impl;

import com.alibaba.fastjson.JSON;
import com.example.apiproject.dao.FeedBackDao;
import com.example.apiproject.entity.FeedBack;
import com.example.apiproject.jwt.jwtutil;
import com.example.apiproject.service.FeedBackService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class FeedBackServiceImpl implements FeedBackService {
    @Autowired
    private jwtutil jwtUtils;

    @Autowired
    private FeedBackDao feedBackDao;
    @Override
    public int insert(HttpServletRequest request, List<String> images, String content) {
        String token = request.getHeader("token");
        if(StringUtils.isBlank(token)){
            token = request.getParameter("token");
        }
        int  userId = jwtUtils.getUserId(token);
        FeedBack feedBack = FeedBack.builder()
                .userId(userId)
                .images(JSON.toJSONString(images))
                .content(content)
                .createTime(LocalDateTime.now()).build();
        return feedBackDao.insert(feedBack);
    }

    @Override
    public int update(FeedBack feedBack) {
//        如果前端传的images不是json字符串，则利用下行代码
//        feedBack.setImages(JSON.toJSONString(feedBack.getImages()));
      return   feedBackDao.update(feedBack);
    }

    @Override
    public List<FeedBack> getByUserId(HttpServletRequest request) {
        String token = request.getHeader("token");
        if(StringUtils.isBlank(token)){
            token = request.getParameter("token");
        }
        int  userId = jwtUtils.getUserId(token);
        return feedBackDao.getByUserId(userId);
    }

    @Override
    public int delete(Integer id) {
        return feedBackDao.delete(id);
    }

    @Override
    public List<FeedBack> queryByStatus(Integer status) {
        return feedBackDao.queryByStatus(status);
    }

    @Override
    public List<FeedBack> queryAll() {
        return feedBackDao.queryAll();
    }

}
